<?php

namespace App\Console\Commands;

use App\Project;
use App\ProjectsReading;
use Carbon\Carbon;
use Facade\FlareClient\Http\Client;
use GuzzleHttp\Client as GuzzleHttpClient;
use Illuminate\Console\Command;

class Reading extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'reading:push';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public $week_ky = [
        0=>'主日',
        1=>'礼拜一',
        2=>'礼拜二',
        3=>'礼拜三',
        4=>'礼拜四',
        5=>'礼拜五',
        6=>'礼拜六',
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {   $time = Carbon::now();
        $project = Project::where('id',1)->first();
        if($p = ProjectsReading::where('read_date',date('Y-m-d'))->first()){
            if($p){
                if($p->chapter){
                $client = new \GuzzleHttp\Client();
                $res = $client->request('GET', 'https://v1api.bible.hi.cn/dailyScriptures/find');
                $body = $res->getBody();
                $index = rand(0,29);
                $bible = json_decode($body,true);
                $content = '';
                $title = '';
                if(isset($bible['data']) && count($bible['data'])>0){
                    $content =  $bible['data'][$index]['content'];
                    $title = $bible['data'][$index]['title'];
                }
                $message = '弟兄姐妹早安\n' .  date('Y年m月d日').'\n（'.$this->week_ky[ $time->dayOfWeek].'）\n 补签编号:' . $p->id .'\n' .  $p->chapter .'\n\n' . $content . '(' .$title .')';
                }
                else{
                 $message = '暂无今日经文，请联系管理员进行添加今日经文';
                }
            }
        }
        else{
            $message = '暂无今日经文，请联系管理员进行添加今日经文';
        }
        $this->sendToGroup($message,$project->wechat_group_id);

    }

    public function sendToGroup($message, $group_id)
    {

        $client = new GuzzleHttpClient();

        $form_data['type'] = 100;
        $form_data['msg']  = urlencode($message);
        $form_data['to_wxid'] = $group_id;
        $form_data['robot_wxid'] = 'wxid_jb6ld4goptbm22';

        $form_data = array('data' => json_encode($form_data));
        
        $res =  $client->post('http://home.iceqi.club:1987/send', ['form_params' => $form_data]);

        return response()->json($res->getBody()->getContents());
    }
}
